#!/usr/bin/perl
use strict;
use loft;
our $IN=$loft::IN;
our $LIST=$loft::LIST;
open IN or die "$IN: $!";
binmode IN;
open LIST,$IN;

my $ptr;
my $pnow=$loft::hdr;
sysread IN,$ptr,$pnow;
printf STDERR "Index at: %d (%x)\n",$ptr,$ptr;
seek LIST,$ptr,0;
open LOUT,'>',$LIST;

while (<LIST>)
{chomp;my ($p1,$p2,$id,$p3,$name)=split / /,$_,5;

my $sr=$p2-$p1;
printf LOUT "%05u %s\n",$id,$name;
warn "Strange: $pnow,$p1,$p3,$p2,$id" if $pnow!=$p1 || $pnow!=$p3;
$pnow+=$sr;

my $rname=loft::rname($name);
warn "$rname exists" if -e $rname;
open DX,'>',$rname or warn "$rname: $!" and next;
binmode DX;
sysseek IN,$p1,0;
for (my $s=1024*1024;$sr>0;$sr-=$s){$s=$sr if $s>$sr;sysread IN,$_,$s;syswrite DX,$_}
close DX;
}
close LIST;
close IN;
warn "Final Gap: $pnow/$ptr" unless $pnow==$ptr;
